clear all;

load('withdraw_deposit.mat','withdraw','deposit','gridtheta','gridb','gridz','nmkt','nz','nb')
farmarketindex=2;
closemarketindex=1;

z=1.16;
[~,zindex]=min(abs(gridz-z));

%% far market
withdraw1=squeeze(withdraw(farmarketindex,zindex,:,:));
deposit1=squeeze(deposit(farmarketindex,zindex,:,:));

x1=gridb';
y1(1:nb,1)=nan;
x2=gridb';
y2(1:nb,1)=nan;

for i=1:nb
    index=find(withdraw1(i,:)==1,1,'last');
    if (~isempty(index))
        y1(i)=index;
    end

    index=find(deposit1(i,:)==1,1,'first');
    if (~isempty(index))
        y2(i)=index;
    end
end

index=find(~isnan(y1));
x1=x1(index);
y1=1-gridtheta(y1(index));

cutoff=find(~isnan(y2)==1,1,'first');
x2=x2(cutoff:end);
y2=1-gridtheta(y2(cutoff:end));

figure;
plot(x1,y1);
hold on
plot(x2,y2);

%% close market
withdraw1=squeeze(withdraw(closemarketindex,zindex,:,:));
deposit1=squeeze(deposit(closemarketindex,zindex,:,:));

x3=gridb';
y3(1:nb,1)=nan;
x4=gridb';
y4(1:nb,1)=nan;

for i=1:nb
    index=find(withdraw1(i,:)==1,1,'last');
    if (~isempty(index))
        y3(i)=index;
    end

    index=find(deposit1(i,:)==1,1,'first');
    if (~isempty(index))
        y4(i)=index;
    end
end

index=find(~isnan(y3));
x3=x3(index);
y3=1-gridtheta(y3(index));

cutoff=find(~isnan(y4)==1,1,'first');
x4=x4(cutoff:end);
y4=1-gridtheta(y4(cutoff:end));

figure;
plot(x3,y3);
hold on
plot(x4,y4);

figure('Color',[1,1,1],'position',[10,20,400,400])
axis square
[row,col]=find(withdraw1==1);
scatter(gridb(row),1-gridtheta(col),[],'b')
hold on
[row,col]=find(deposit1==1);
scatter(gridb(row),1-gridtheta(col),[],'b')



save('panelB.mat','x1','x2','x3','x4','y1','y2','y3','y4')